<?php
/**
 * Created By virus_cms
 * Author: Virus
 * Date: 2020/3/2
 * Time: 14:09
 */

namespace app\common\lib;


use app\BaseController;
use think\db\exception\DbException;
use think\facade\Db;

class BaseMethod extends BaseController
{
    // CRUD 增删改查

    /**
     * 增
     * @param $tableName
     * @param $data
     * @return int|string
     */
    public function Create($tableName, $data)
    {
        try {
            return Db::name($tableName)->strict(false)->insert($data);
        } catch (DbException $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * 查
     * @param $tableName
     * @param $key
     * @param $value
     * @return string|\think\Collection
     */
    public function Retrieve($tableName, $key, $value)
    {
        try {
            return Db::name($tableName)->where($key, $value)->select();
        } catch (DbException $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * 改
     * @param $tableName
     * @param $id
     * @param $data
     * @return int|string
     */
    public function Update($tableName, $id, $data)
    {
        try {
            return Db::name($tableName)->where('id', $id)->update($data);
        } catch (DbException $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * 删
     * @param $tableName
     * @param $id
     * @return int|string
     */
    public function Delete($tableName, $id)
    {
        try {
            return Db::name($tableName)->where('id', $id)->delete();
        } catch (DbException $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * @desc 遍历
     * @param $tableName
     * @return array
     */
    public function throwAll($tableName)
    {
        $sql = "SELECT * FROM `$tableName`";

        return Db::query($sql);
    }

    /**
     * 批量删除
     * @param $tableName
     * @param $ids
     * @return int|string
     */
    public function batchDelete($tableName, $ids)
    {
        try {
            foreach ($ids as $id) {
                return Db::name($tableName)->where('id', $id)->delete();
            }
        } catch (DbException $exception) {
            return $exception->getMessage();
        }
    }
}